<template>
  <span>
    <el-col
      v-for="(item, index) in form.exchangeRate"
      :key="new Date().getTime() + '_' + index"
      :span="12"
    >
      <el-form-item :prop="'exchangeRate.' + index + '.rate'" :rules="[{ required: true, message: $t('必填信息'), trigger: ['blur', 'change'] }]">
        <span slot="label">
          {{ $t(formatCurrency(item.sourceCurrency)) }}{{ $t('对') }}{{ $t(formatCurrency(item.targetCurrency)) }}{{ $t('汇率') }}
          <el-tooltip :content="$t('使用') + item.placeholder" placement="right">
            <el-button
              v-if="item.placeholder !== undefined && item.placeholder !== null && item.placeholder !== ''"
              class="el-icon-document-copy"
              size="small"
              type="text"
              style="color: #1890ff !important;cursor: pointer;"
              @click="inputPlaceholder(index, item.placeholder)"
            />
          </el-tooltip>
        </span>
        <el-input-number
          v-model="item.rate"
          :max="999999999"
          :min="0"
          :controls="false"
          :placeholder="item.placeholder"
          @change="changeBlurRate($event, item)"
          @blur="changeBlurRate($event, item)"
        />
      </el-form-item>
    </el-col>
  </span>
</template>

<script>
import { getWebRate } from '@/api/deal/investment/dealInvestment'

/**
 * 说明:
 *  将该组件引入Form表单, 引入props中的元素即可自动弹出汇率输入框
 *  注: form.currency 必须有值, 且保存后会set值到exchangeRate, 故表中要创建该字段
 */
export default {
  components: {},
  props: {
    // 表单 该Form中必须包含form.currency, 且不能为空
    form: {
      type: Object,
      default: () => {},
      required: true
    },
    // 主体 ['CNY', 'USD', ....]
    currencyList: {
      type: Array,
      default: () => [],
      required: true
    }
  },
  data() {
    return {
      // 遮盖层
      loading: false,
      currencyOptions: []
    }
  },
  watch: {
    form: {
      handler(val) {
        this.$parent.$parent.$parent.form.exchangeRate = val.exchangeRate
      },
      deep: true,
      immediate: true
    },
    currencyList: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.setRateByInvestor()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
    })
  },
  methods: {
    /** 选中近期汇率 **/
    inputPlaceholder(index, val) {
      if (val !== undefined && val !== null && val !== '') {
        val = val.replaceAll('近期汇率参考', '').replaceAll(':', '').trim()
        this.$set(this.form.exchangeRate[index], 'rate', parseFloat(val))
        this.$forceUpdate()
      }
    },
    /** 手动修改汇率 **/
    changeBlurRate(val, item) {
      if (val === undefined || val === '' || val === null) {
        val = 0
      }
      if (!isNaN(val)) {
        const index = this.form.exchangeRate.findIndex(obj => (obj.sourceCurrency === item.sourceCurrency && obj.targetCurrency === item.targetCurrency))
        this.$nextTick(() => {
          this.form.exchangeRate[index].rate = (val === 0 ? undefined : val)
          this.$forceUpdate()
        })
      }
    },
    /** 根据出资主体列表动态更新汇率 **/
    setRateByInvestor() {
      console.log('根据出资主体列表动态更新汇率')
      this.form.exchangeRate = []
      if (!this.isEmpty(this.currencyList)) {
        var currencyList = Array.from(new Set(this.currencyList))
        if (!this.isEmpty(this.form.currency)) {
          currencyList.forEach(item => {
            if (item !== this.form.currency) {
              this.form.exchangeRate.push({
                sourceCurrency: item,
                targetCurrency: this.form.currency,
                rate: undefined
              })
            }
          })
        }
        // 后台获取汇率
        this.getWebRate()
      }
    },
    /** 后台获取汇率 **/
    getWebRate() {
      this.form.exchangeRate.forEach((item, index) => {
        if (item !== undefined && item.targetCurrency !== undefined && item.sourceCurrency !== undefined) {
          getWebRate(item.targetCurrency, item.sourceCurrency, this.parseTime(new Date())).then(response => {
            if (response.data !== '' && response.data !== null) {
              item.placeholder = response.data
              this.$set(this.form.exchangeRate[index], 'placeholder', this.$t('近期汇率参考') + ': ' + response.data)
              this.$forceUpdate()
            }
          })
        }
      })
    },
    /** 币种字典 **/
    formatCurrency(val) {
      const currency = this.currencyOptions.find(obj => obj.dictValue === val)
      if (currency) {
        return currency.dictLabel
      }
      return val
    }
  }
}
</script>

<style scoped>

</style>
